import React, { useRef, useState } from 'react';
import { ProTable, ActionType } from '@ant-design/pro-components';
import { Button, Modal, message, Tag, Tooltip, Space, Form, InputNumber, Input } from 'antd';
import { CreditCardOutlined, LockOutlined, StopOutlined, CheckCircleOutlined, DollarOutlined, KeyOutlined, UnlockOutlined } from '@ant-design/icons';
import * as customerController from '@/services/backend/customerController';
import * as cardController from '@/services/backend/cardController';

interface Card {
  cardId: string;
  balance: number | string;
  isReportLoss: number;
  currency: string;
  openDate: string;
}

const CardsPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(false);
  const [depositModal, setDepositModal] = useState<{visible: boolean, cardId?: string}>({visible: false});
  const [withdrawModal, setWithdrawModal] = useState<{visible: boolean, cardId?: string}>({visible: false});
  const [passwordModal, setPasswordModal] = useState<{visible: boolean, cardId?: string}>({visible: false});
  const [transferModal, setTransferModal] = useState<{visible: boolean, fromCardId?: string}>({visible: false});
  const [depositForm] = Form.useForm();
  const [withdrawForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [transferForm] = Form.useForm();

  // 挂失/解挂
  const handleReportLoss = async (cardId: string, isReportLoss: number) => {
    try {
      setLoading(true);
      await customerController.reportCardLoss(cardId);
      message.success(isReportLoss ? '挂失成功' : '解挂成功');
      actionRef.current?.reload();
    } catch (e) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 存款
  const handleDeposit = async (values: any) => {
    try {
      setLoading(true);
      await customerController.customerDeposit(depositModal.cardId!, { amount: values.amount, remark: values.remark });
      message.success('存款成功');
      setDepositModal({visible: false});
      actionRef.current?.reload();
    } catch (e) {
      message.error('存款失败');
    } finally {
      setLoading(false);
      depositForm.resetFields();
    }
  };

  // 取款
  const handleWithdraw = async (values: any) => {
    console.log('取款表单提交', values);
    try {
      setLoading(true);
      await customerController.customerWithdraw({ cardId: withdrawModal.cardId!, amount: values.amount, password: values.password, remark: values.remark });
      message.success('取款成功');
      setWithdrawModal({visible: false});
      actionRef.current?.reload();
    } catch (e) {
      message.error('取款失败');
    } finally {
      setLoading(false);
      withdrawForm.resetFields();
    }
  };

  // 修改密码
  const handlePassword = async (values: any) => {
    try {
      setLoading(true);
      await customerController.updateCardPassword({ cardId: passwordModal.cardId!, oldPassword: values.oldPassword, newPassword: values.newPassword });
      message.success('密码修改成功');
      setPasswordModal({visible: false});
    } catch (e) {
      message.error('密码修改失败');
    } finally {
      setLoading(false);
      passwordForm.resetFields();
    }
  };

  // 转账
  const handleTransfer = async (values: any) => {
    try {
      setLoading(true);
      await customerController.customerTransfer({
        fromCardId: transferModal.fromCardId!,
        toCardId: values.toCardId,
        amount: values.amount,
        password: values.password,
        remark: values.remark
      });
      message.success('转账成功');
      setTransferModal({visible: false});
      actionRef.current?.reload();
    } catch (e: any) {
      // 添加具体的错误提示
      if (e.response?.data?.error === 'Receiver card not found') {
        Modal.error({
          title: '收款卡号不存在',
          content: '您输入的收款卡号不存在，请确认卡号是否正确。',
        });
      } else if (e.response?.data?.error === 'Insufficient balance') {
        Modal.error({
          title: '余额不足',
          content: '您的账户余额不足，无法完成此次转账。',
        });
      } else if (e.response?.data?.error === 'Invalid card status') {
        Modal.error({
          title: '卡片状态异常',
          content: '您的银行卡状态异常，无法进行转账操作。',
        });
      } else {
        Modal.error({
          title: '转账失败',
          content: e.message || '转账过程中发生未知错误，请重试。',
        });
      }
    } finally {
      setLoading(false);
      transferForm.resetFields();
    }
  };

  return (
    <>
      <ProTable
        actionRef={actionRef}
        rowKey="cardId"
        columns={[
          { 
            title: '卡号',
            dataIndex: 'cardId',
            copyable: true,
            search: {
              transform: (value) => {
                return value ? { cardId: value } : {};
              }
            }
          },
          { 
            title: '余额', 
            dataIndex: 'balance', 
            render: (_: any, record: Card) => {
              const amount = parseFloat(String(record.balance));
              return isNaN(amount) ? '¥0.00' : `¥${amount.toFixed(2)}`;
            },
            search: {
              transform: (value: any) => {
                if (!value || !Array.isArray(value)) return {};
                const [min, max] = value;
                return {
                  minBalance: min ? parseFloat(min) : undefined,
                  maxBalance: max ? parseFloat(max) : undefined
                };
              }
            },
            valueType: 'digitRange',
            fieldProps: {
              precision: 2,
              formatter: (value: number | undefined) => value ? `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '',
              parser: (value: string) => value.replace(/\$\s?|(,*)/g, '')
            }
          },
          { title: '状态', dataIndex: 'isReportLoss', valueType: 'select', valueEnum: {
            0: { text: '正常', status: 'Success' },
            1: { text: '已挂失', status: 'Error' },
          }, render: (_, record) => <Tag color={record.isReportLoss ? 'red' : 'green'}>{record.isReportLoss ? '已挂失' : '正常'}</Tag> },
          {
            title: '操作',
            valueType: 'option',
            render: (_, record: Card) => (
              <Space>
                {record.isReportLoss === 0 ? (
                  <>
                    <Button
                      type="link"
                      icon={<DollarOutlined />}
                      onClick={() => setDepositModal({visible: true, cardId: record.cardId})}
                    >
                      存款
                    </Button>
                    <Button
                      type="link"
                      icon={<DollarOutlined />}
                      onClick={() => setWithdrawModal({visible: true, cardId: record.cardId})}
                    >
                      取款
                    </Button>
                    <Button
                      type="link"
                      icon={<DollarOutlined />}
                      onClick={() => setTransferModal({visible: true, fromCardId: record.cardId})}
                    >
                      转账
                    </Button>
                    <Button
                      type="link"
                      danger
                      icon={<LockOutlined />}
                      onClick={() => handleReportLoss(record.cardId, 1)}
                    >
                      挂失
                    </Button>
                  </>
                ) : (
                  <Button
                    type="link"
                    icon={<UnlockOutlined />}
                    onClick={() => handleReportLoss(record.cardId, 0)}
                  >
                    解挂
                  </Button>
                )}
                <Button
                  type="link"
                  icon={<KeyOutlined />}
                  onClick={() => setPasswordModal({visible: true, cardId: record.cardId})}
                >
                  改密
                </Button>
              </Space>
            )
          },
          {
            title: '开卡时间',
            dataIndex: 'openDate',
            valueType: 'dateTime',
            search: false,
            width: 180,
          },
        ]}
        request={async (params) => {
          // 移除空值参数
          const queryParams = Object.fromEntries(
            Object.entries({
              page: params.current,
              size: params.pageSize,
              cardId: params.cardId,
              minBalance: params.minBalance,
              maxBalance: params.maxBalance,
              isReportLoss: params.isReportLoss,
            }).filter(([_, value]) => value !== undefined && value !== null && value !== '')
          );

          try {
            const response = await customerController.getMyCardList(queryParams);
            if (response.code === 1) {
              return {
                data: response.data.records,
                success: true,
                total: response.data.total
              };
            } else {
              message.error(response.msg || '获取银行卡列表失败');
              return {
                data: [],
                success: false,
                total: 0
              };
            }
          } catch (error) {
            message.error('获取银行卡列表失败');
            return {
              data: [],
              success: false,
              total: 0
            };
          }
        }}
        search={{ labelWidth: 80 }}
        pagination={{ showQuickJumper: true }}
        toolBarRender={() => [
          <Button key="refresh" onClick={() => actionRef.current?.reload()}>刷新</Button>
        ]}
      />
      {/* 存款模态框 */}
      <Modal
        title="存款"
        open={depositModal.visible}
        onCancel={() => { setDepositModal({visible: false}); depositForm.resetFields(); }}
        onOk={() => depositForm.submit()}
        okText="确认存款"
        confirmLoading={loading}
      >
        <Form form={depositForm} onFinish={handleDeposit} layout="vertical">
          <Form.Item name="amount" label="存款金额" rules={[{ required: true, message: '请输入金额' }]} validateTrigger={['onBlur','onChange']}>
            <InputNumber min={0.01} precision={2} step={0.01} style={{width:'100%'}} onPressEnter={() => depositForm.submit()} />
          </Form.Item>
          <Form.Item name="remark" label="备注"> <Input /> </Form.Item>
        </Form>
      </Modal>
      {/* 取款模态框 */}
      <Modal
        title="取款"
        open={withdrawModal.visible}
        onCancel={() => { setWithdrawModal({visible: false}); withdrawForm.resetFields(); }}
        onOk={() => withdrawForm.submit()}
        okText="确认取款"
        confirmLoading={loading}
      >
        <Form form={withdrawForm} onFinish={handleWithdraw} layout="vertical">
          <Form.Item name="amount" label="取款金额" rules={[{ required: true, message: '请输入金额' }]} validateTrigger={['onBlur','onChange']}>
            <InputNumber min={0.01} precision={2} step={0.01} style={{width:'100%'}} onPressEnter={() => withdrawForm.submit()} />
          </Form.Item>
          <Form.Item name="password" label="银行卡密码" rules={[{ required: true, message: '请输入密码' }]} validateTrigger={['onChange','onBlur']}>
            <Input.Password />
          </Form.Item>
          <Form.Item name="remark" label="备注"> <Input /> </Form.Item>
        </Form>
      </Modal>
      {/* 修改密码模态框 */}
      <Modal
        title="修改银行卡密码"
        open={passwordModal.visible}
        onCancel={() => { setPasswordModal({visible: false}); passwordForm.resetFields(); }}
        onOk={() => passwordForm.submit()}
        okText="确认修改"
        confirmLoading={loading}
      >
        <Form form={passwordForm} onFinish={handlePassword} layout="vertical">
          <Form.Item 
            name="oldPassword" 
            label="当前密码" 
            rules={[{ required: true, message: '请输入当前密码' }]}
            validateTrigger={['onBlur','onChange']}
          > 
            <Input.Password onPressEnter={() => passwordForm.submit()} autoComplete="current-password" /> 
          </Form.Item>
          <Form.Item 
            name="newPassword" 
            label="新密码" 
            rules={[{ required: true, message: '请输入新密码' }, { pattern: /^\d{6}$/, message: '新密码必须是6位数字' }]}
            validateTrigger={['onBlur','onChange']}
          > 
            <Input.Password onPressEnter={() => passwordForm.submit()} autoComplete="new-password" /> 
          </Form.Item>
          <Form.Item 
            name="confirmPassword" 
            label="确认新密码" 
            dependencies={["newPassword"]}
            rules={[ 
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的新密码不一致!'));
                },
              })
            ]}
            validateTrigger={['onBlur','onChange']}
          > 
            <Input.Password onPressEnter={() => passwordForm.submit()} autoComplete="new-password" /> 
          </Form.Item>
        </Form>
      </Modal>
      {/* 转账模态框 */}
      <Modal
        title="转账"
        open={transferModal.visible}
        onCancel={() => { setTransferModal({visible: false}); transferForm.resetFields(); }}
        onOk={() => transferForm.submit()}
        okText="确认转账"
        confirmLoading={loading}
      >
        <Form form={transferForm} onFinish={handleTransfer} layout="vertical">
          <Form.Item name="toCardId" label="收款卡号" rules={[{ required: true, message: '请输入收款卡号' }]} validateTrigger={['onBlur','onChange']}>
            <Input onPressEnter={() => transferForm.submit()} />
          </Form.Item>
          <Form.Item name="amount" label="转账金额" rules={[{ required: true, message: '请输入金额' }]} validateTrigger={['onBlur','onChange']}>
            <InputNumber min={0.01} precision={2} step={0.01} style={{width:'100%'}} onPressEnter={() => transferForm.submit()} />
          </Form.Item>
          <Form.Item name="password" label="银行卡密码" rules={[{ required: true, message: '请输入密码' }]} validateTrigger={['onBlur','onChange']}>
            <Input.Password onPressEnter={() => transferForm.submit()} />
          </Form.Item>
          <Form.Item name="remark" label="备注"> <Input onPressEnter={() => transferForm.submit()} /> </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default CardsPage; 